package cc.messcat.service.area;

import cc.messcat.common.model.Pager;
import cc.messcat.common.service.BaseServiceImpl;
import cc.messcat.dao.area.AreaDao;
import cc.messcat.entity.area.Area;
import cc.messcat.entity.system.McUser;
import cc.messcat.util.Collections;
import cc.messcat.util.LevelUtil;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AreaServiceImpl extends BaseServiceImpl<Area> implements AreaService {

    @Autowired
    private AreaDao areaDao;
    
	@Autowired
	private CacheManager cacheManager;


    @Override
    public List<Area> findAreasByParentId(Long parentId) {
        return areaDao.getAreasByParentId(parentId);
    }

    @Override
    public Area getByAreaID(Long areaID) {
        return areaDao.getByID(areaID);
    }

    @Override
    @SuppressWarnings("all")
    public List retrieveAllarea(Long fatherId) {
    	//先查缓存
    	Element element = cacheManager.getCache("areaCache").get("allAreaByFatherId");
		if(element != null) {
			Map<Long,List<Area>> areaCache = (Map<Long, List<Area>>) element.getObjectValue();
			List<Area> list = areaCache.get(fatherId);
			return list == null ? new ArrayList<>(0) : list;
		}
    	
        Map map = new HashMap<>();
        String hql = "from Area where fatherId = " + fatherId;
        map.put("fatherId", fatherId);
        return this.areaDao.queryList(hql, map);
    }

    @Override
    public List retrieveAreaById(Long id) {
        Map map = new HashMap<>();
        String hql = "from Area where id = " + id;
        map.put("id", id);
        return this.areaDao.queryList(hql, map);
    }

    @Override
    public void removearea(Long id) {
        removeObject(id);
    }

    @Override
    public void addArea(Area area) {
        addObject(area);
    }

    @Override
    public void modifyArea(Area area) {

        modifyObject(area);
    }

    @Override
    public List retrieveAreaByIdfathid(Long id, Long fatherId) {
        Map map = new HashMap<>();
        String hql = "from Area where id ='" + id + "'  and fatherId ='" + fatherId + "'";
        map.put("id", id);
        map.put("fatherId", fatherId);
        return this.areaDao.queryList(hql, map);
    }

    @Override
    public Pager<Area> getPage(Long fatherId, int pageNo, int pageSize) {
        Map map = new HashMap<>();
        String hql = "from Area where fatherId = " + fatherId;
        map.put("fatherId", fatherId);
        return this.areaDao.getPagerByHql(pageNo, pageSize, hql, map);

    }

    @Override
    public Pager<Area> retrieveAllvaguearea(Integer pageNo, Integer pageSize, Long fatherId, String area, String areaCode) {
        Map map = new HashMap<>();
        StringBuffer hql = new StringBuffer();
        hql.append("FROM Area WHERE 1=1 ");
        if (fatherId != null && !"".equals(fatherId)) {
            hql.append(" AND fatherId ='" + fatherId + "'");
        }
        if (area != null && !"".equals(area)) {
            area = area.replaceAll(" ", "");
            hql.append(" AND area like '%" + area + "%'");
        }
        if (areaCode != null && !"".equals(areaCode)) {
            areaCode = areaCode.replaceAll(" ", "");
            hql.append(" AND areaCode like '%" + areaCode + "%'");
        }
        if(fatherId==null&&!"".equals(fatherId)){
        	 hql.append(" AND fatherId > 3 ");
        	 Pager<Area> village = areaDao.getPagerByHql(pageNo, pageSize, hql.toString(), map);
        	 return village;
        }

        return this.areaDao.getPagerByHql(pageNo, pageSize, hql.toString(), map);
    }

    @Override
    public List<Area> getAreaHasVillageInfo(Long fatherId) {

        return areaDao.getAreaHasVillageInfo(fatherId);

    }

    @Override
    public Area getAreaByName(String name) {

        return areaDao.getAreaByName(name);

    }

	@Override
	public Area getAreaByCode(String areaCode) {
		return  areaDao.getAreaByCode(areaCode);
	}

	@Override
	public Area getAreaByName(String name, String village) {
		List areas = areaDao.find("from Area as a1 where fatherId = (select id from Area as a where a.area = '"+name+"') and a1.area = '"+village+"' ");
		return (Area) (Collections.isEmpty(areas) ? null : areas.get(0));
	}

	/**
	 * 根据登录用户获取区域
	 * @return
	 */
	@Override
	public List<Area> areaAuthorization(McUser user, Long fatherId) {
		if(!"未审核".equals(user.getCheckState())){
			Area userArea = user.getArea();
			Integer level = user.getUserLevel().getLevel();
			if(level < LevelUtil.TOWN) {
				return findAreasByParentId(fatherId);
			}
			//权限信息错误
			if(level > LevelUtil.COUNTY && userArea == null) {
				return new ArrayList<>(0);
			}
			String areaCode = userArea.getAreaCode();
			
			if(fatherId == 3 && level >= LevelUtil.TOWN) {
				areaCode = StringUtils.isNotBlank(areaCode) && areaCode.length() > 8 ? areaCode.substring(0, 9) + "%" : "none area";
				return areaDao.areaAuthorization(areaCode);
			}
			
			if(fatherId > 3 && level >= LevelUtil.TOWN ) {
				String areaCodeCondition = StringUtils.isNotBlank(areaCode) && areaCode.length() > 8 ? areaCode.substring(0, 9) + "%" : "none area";
				List<Area> areas = areaDao.areaAuthorization(areaCodeCondition);
				if(fatherId != (areas != null && !areas.isEmpty() ? areas.get(0).getId() : -1L)) {
					return new ArrayList<Area>();
				}
				if(level == LevelUtil.VILLAGE) {
					List<Area> result = new ArrayList<>();
					result.add(getAreaByCode(areaCode));
					return result; 
				}
				return findAreasByParentId(fatherId);
			}
			
			return findAreasByParentId(fatherId);
		}
		return new ArrayList<Area>();
	}

	/**
	 * 获取区域全表数据
	 * @return
	 */
	@Override
	public List<Area> getAllArea() {
		return areaDao.find(" from Area");
	}

	/**
	 * 获取所有的村
	 */
    @Override
    public List<Area> getALLVillage() {
        return areaDao.find(" from Area where fatherId in(from Area where fatherId=3)");
    }


}
